package com.zmm.util.auth.registry;

import com.zmm.common.constant.Constant;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolverComposite;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @author 900045
 * @description:
 * @name ReqParamResolverComposite
 * @date By 2021-09-28 10:54:02
 */
public class ReqParamResolverComposite extends HandlerMethodArgumentResolverComposite {

	private Logger logger = LoggerFactory.getLogger(ReqParamResolverComposite.class);

	/**
	 *  判断某个参数是否包含某个注解
	 * @see org.springframework.web.method.support.HandlerMethodArgumentResolver#supportsParameter(org.springframework.core.MethodParameter)
	 */
	@Override
	public boolean supportsParameter(MethodParameter parameter) {

		return parameter.getParameterType().isPrimitive();
	}

	/**
	 * 注解参数 校验绑定
	 * @see
	 */
	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
								  NativeWebRequest webRequest,
								  WebDataBinderFactory binderFactory) throws Exception {
		String name = null;
		if (webRequest == null || (name = parameter.getParameterName()) == null) {
			return null;
		}
		String value = webRequest.getParameter(name);
		Class<?> parameterType = parameter.getParameterType();

		logger.info("PS-resolveArgument-1:{} - {}", name, value);

		if (StringUtils.isBlank(value) || Constant.NULL.equals(value)) {
			logger.info("PS-resolveArgument-2:{} - {}", name, value);
			return Integer.parseInt("0");
		}
		if (parameterType.getName().equals(Constant.INT)) {
			return Integer.parseInt(value);
		} else if (parameterType.getName().equals(Constant.LONG)) {
			return Long.parseLong(value);
		} else if (parameterType.getName().equals(Constant.SHORT)) {
			return Short.parseShort(value);
		} else if (parameterType.getName().equals(Constant.DOUBLE)) {
			return Double.parseDouble(value);
		} else if (parameterType.getName().equals(Constant.BYTE)) {
			return Byte.parseByte(value);
		}
		return value;

	}
}
